<template>
  <div>
    <el-card>
      <template #header>
        <div class="searchHead">
          <el-form :model="form" inline>
            <!-- <el-form-item label="选择公司" :label-width="formLabelWidth">
            <el-select
              v-model="form.enterpriseCode"
              filterable
              clearable
              placeholder="请选择公司名称"
              :disabled = "isdisable"
            >
              <el-option
                v-for="item in options"
                :key="item.enterpriseId"
                :label="item.cmpName"
                :value="item.enterpriseCode"
              />
            </el-select>
          </el-form-item> -->
            <el-form-item label="数据编码">
              <el-input v-model="form.code" class="w-50 m-2" placeholder="请输入数据编码" clearable @change="columnChange" style="width: 200px">
                <template #prefix>
                  <el-icon class="el-input__icon">
                    <search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="数据统计时间">
              <!-- <el-date-picker
                v-model="form.date"
                type="datetime"
                placeholder="请选择日期"
                @change="columnChange"
              /> -->
              <el-date-picker v-model="form.date" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间"
                :default-time="defaultTime2" @change="columnChange" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="margin-right: 10px" @click="dialogFormVisible = true">
                导出数据<el-icon class="el-input__icon">
                  <Plus />
                </el-icon>
              </el-button>
              <el-upload class="upload-demo" action="none" :show-file-list="false" :auto-upload="false" multiple
                         accept=".xlsx, .xls"
                         :before-upload="beforeUpload"
                :on-change="uploadFile">
                <el-button type="primary">导入数据</el-button>
              </el-upload>
              <el-button type="primary" style="margin-right: 10px" @click="downloadTemp">
                导出模板<el-icon class="el-input__icon">
                  <Plus />
                </el-icon>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <el-table ref="enterpriseRef" :data="tableData" style="width: 100%; max-height: 61vh; height: 61vh"
        table-layout="auto" v-loading="loading" :row-class-name="tableRowClassName"
         :header-cell-style="{'text-align':'center'}"
         :cell-style="{'text-align':'center'}"> 
        <el-table-column fixed prop="enterName" label="公司名称" />
        <el-table-column prop="collectitemName" label="采集数据项名称" />
        <el-table-column prop="dataCode" label="上报数据项编码" />
        <el-table-column prop="dataValue" label="上传数据" />
        <el-table-column prop="convertRation" label="折标系数" />
        <el-table-column prop="dataIndex" label="端系统记录索引" show-overflow-tooltip/>
        <el-table-column prop="remark" label="备注" show-overflow-tooltip/>
        <el-table-column prop="statDate" label="数据统计时间" />
        <el-table-column prop="uploadDate" label="数据上报时间" />
        <!-- <el-table-column fixed="right" label="操作" width="160">
          <template #default="scope">
            <el-button
              link
              type="primary"
              size="small"
              @click="updata(scope.$index, scope.row)"
              >上报</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="handleClick(scope.$index, scope.row)"
              >日志</el-button
            >
            <el-button
              link
              type="primary"
              size="small"
              @click="rowChange(scope.$index, scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column> -->
      </el-table>
      <div class="card-footer">
        <el-pagination layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,30,40,50,100,500]"
          background v-model:page-size="pagination.size"
          v-model:current-page="pagination.page" :total="pagination.total" @size-change="sizeChange"
          @current-change="pageChange" class="pagination" />
      </div>
      <!-- 修改信息对话框 -->
      <el-dialog v-model="dialogFormVisible" title="导出文件" style="max-width: 350px" :destroy-on-close="true">
        <el-form :model="uploadForm" label-width="80">
          <el-form-item label="选择公司" :label-width="formLabelWidth">
            <el-select v-model="uploadForm.enterpriseCode" filterable clearable placeholder="请选择公司名称"
              @change="columnChange" :disabled="isdisable">
              <el-option v-for="item in options" :key="item.enterpriseId" :label="item.cmpName"
                :value="item.enterpriseCode" :disabled="isdisable"/>
            </el-select>
          </el-form-item>
          <el-form-item label="日期">
            <el-date-picker v-model="uploadForm.statDate" type="month" placeholder="请选择导出时间段" format="YYYY-MM"
              value-format="YYYY-MM" @change="columnChange" />
          </el-form-item>
          <el-form-item label="是否上报">
            <el-select v-model="uploadForm.dataIndex" class="m-2" placeholder="请选择数据">
              <el-option v-for="item in dataindexOption" :key="item.id" :label="item.label" :value="item.id" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="downLoadFile"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="tempFileVisibel" title="导出文件" style="max-width: 350px" :destroy-on-close="true">
        <el-form :model="uploadForm" label-width="80">
          <el-form-item label="选择公司" :label-width="formLabelWidth">
            <el-select v-model="uploadForm.enterpriseCode" filterable clearable placeholder="请选择公司名称"
              :disabled="isdisable">
              <el-option v-for="item in options" :key="item.enterpriseId" :label="item.cmpName"
                :value="item.enterpriseCode" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="tempFileVisibel = false">取消</el-button>
            <el-button type="primary" @click="downloadTempFile"> 确定 </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import axios from "axios";
import { reactive, ref } from "vue";
import { formatDateTime } from "@/utils";
import { getNameList } from "@/api/enterprise";
import { get } from "@/api/enterpriseEnergyList";
import { ElMessage } from "element-plus";
import useStore from "@/store";
import { storeToRefs } from "pinia";
let defaultTime2 = [];
const form = reactive({
  keyWord: "",
  code: "",
  date: [],
});
const Store = useStore();
const { userInfo } = storeToRefs(Store);
const isdisable = ref(false);
const uploadForm = reactive({
  enterpriseCode: "",
  statDate: "",
  dataIndex: "",
});
const tempFileVisibel = ref(false);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

const dataindexOption = ref([
  { id: 0, label: "未上报" },
  { id: 1, label: "已上报" },
  { id: 3, label: "导出所有" },
]);
const tableRowClassName = (row, rowindex) => {
  if (row.row.dataIndex === "") {
    return "warning-row";
  }
  return "";
};
const tableData = ref([]);
const loading = ref(true);
const options = ref([]);
const userDisabled = ref(false)
const conditions = ref([]);
const dialogFormVisible = ref(false);
const doFilterUser = () => {
  let condi =[];
  if (userInfo.value.roleId != "3") {

    let temp = {
      column: "enterpriseCode",
      type: "eq",
      value: userInfo.value.userName,
    };
    condi.push(temp);
  }
  conditions.value = condi;
}
const doDataList = () => {
  let start = new Date();
  let end = new Date();
  start.setHours(0);
  start.setMinutes(0);
  start.setSeconds(0);
  end.setHours(23);
  end.setMinutes(59);
  end.setSeconds(59);
  defaultTime2 = [start, end];
  loading.value = true;
  getNameList()
    .then((res) => {
      doUserFilter()
      options.value = res.data;
      let datas = {
        pageNum: pagination.page,
        pageSize: pagination.size,
        condition: JSON.stringify(conditions.value),
      };
      get(datas)
        .then((res) => {
          //获取到信息
          tableData.value = res.data.records;
          pagination.size = res.data.pageSize;
          pagination.page = res.data.currentPage;
          pagination.total = res.data.total;
          //请求完成,开始处理数据
          doEnterName();
          loading.value = false;
        })
        .catch((msg) => {
          //获取出错
          ElMessage.error("获取信息失败，请联系管理员！");
        });
    })
    .catch((msg) => {
      console.log();
    });
};
const getList = () => {
  loading.value = true;
  let datas = {
    pageNum: pagination.page,
    pageSize: pagination.size,
    condition: JSON.stringify(conditions.value),
  };
  get(datas)
    .then((res) => {
      //获取到信息
      tableData.value = res.data.records;
      pagination.size = res.data.pageSize;
      pagination.page = res.data.currentPage;
      pagination.total = res.data.total;
      doEnterName();
      loading.value = false;
    })
    .catch((msg) => {
      //获取出错
    });
};
const doEnterName = () => {
  let tempTableData = tableData.value;
  let tempOptions = options.value;
  for (let i = 0; i < tempTableData.length; i++) {
    for (let j = 0; j < tempOptions.length; j++) {
      if (tempTableData[i].enterpriseCode === tempOptions[j].enterpriseCode) {
        tempTableData[i].enterName = tempOptions[j].cmpName;
      }
    }
  }
  tableData.value = tempTableData;
};

const downLoadFile = () => {
  axios
    // .get("https://www.bknyjk.com:5173/api/energy/exportExcel", {
    //   params: uploadForm,
    //   responseType: "blob",
    // })
    .get("http://localhost:5173/api/energy/exportExcel", {
      params: uploadForm,
      responseType: "blob",
    })
    .then((res) => {
      const fileName = uploadForm.enterpriseCode + "_" + uploadForm.statDate;
      const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); //设置下载的内容以及格式
      const url = window.URL.createObjectURL(blob); //设置路径
      const link = window.document.createElement("a"); // 创建a标签
      link.href = url;
      // let filename = res.headers['content-disposition']
      //   .split(';')[1]
      //   .split('filename=')[1]
      // let decodedURL = decodeURIComponent(filename); //解码，返回的是文件流所以我从res.header里面拿的文件名，但是是编码后的%E4，所以拿来用的话要在前端解码
      link.download = fileName; //设置文件名
      link.style.display = "none";
      link.click();
      URL.revokeObjectURL(url);
    })
    .catch((err) => { });
};

const beforeUpload= (file)  =>  {
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
        this.$message.error('上传的文件大小不能超过 1M!');
    }
    return isLt1M;
}
const uploadFile = (file, fileList) => {
  const formData = new FormData();
  formData.append("file", file.raw);
  axios
    // .post("https://www.bknyjk.com:5173/api/energy/importExcel", formData, {
    //   "Content-type": "multipart/form-data",
    // })
    .post("http://localhost:5173/api/energy/importExcel", formData, {
      "Content-type": "multipart/form-data",
    })
    .then(
      (res) => {
        console.log(res.data.status)
        if(res.data.status === 200){
            ElMessage.success("上传成功！");
        }else{
        // 上传成功后的处理
            ElMessage.error(res.data.message)
        }
      }
    );
};
const doUserFilter = () =>{
  let user = userInfo.value
  if (user.roleId == "1") {
    uploadForm.enterpriseCode = user.userName;
    isdisable.value = true;
  }
}
const downloadTemp = () => {
  let user = userInfo.value
  tempFileVisibel.value = true;
  if (user.roleId == "1") {
    uploadForm.enterpriseCode = user.userName;
    isdisable.value = true;
  }

}
const downloadTempFile = () => {
  axios
    .get("https://www.bknyjk.com:5173/api/datacollectconfigure/exportExcelTemplate", {
      params: uploadForm,
      responseType: "blob",
    })
    .then((res) => {
      const fileName = uploadForm.enterpriseCode + "_" + uploadForm.statDate;
      const blob = new Blob([res.data], { type: "application/vnd.ms-excel" }); //设置下载的内容以及格式
      const url = window.URL.createObjectURL(blob); //设置路径
      const link = window.document.createElement("a"); // 创建a标签
      link.href = url;
      // let filename = res.headers['content-disposition']
      //   .split(';')[1]
      //   .split('filename=')[1]
      // let decodedURL = decodeURIComponent(filename); //解码，返回的是文件流所以我从res.header里面拿的文件名，但是是编码后的%E4，所以拿来用的话要在前端解码
      link.download = fileName; //设置文件名
      link.style.display = "none";
      link.click();
      URL.revokeObjectURL(url);
    })
    .catch((err) => { });
}
/**
 * 页数据总数改变
 */
const sizeChange = (value) => {
  pagination.size = value;
  pagination.page = 1;
  getList();
};
/**
 * 页总数改变
 */
const pageChange = (value) => {
  pagination.page = value;
  getList();
};
const handlePreview = (uploadFile) => { };
const handleRemove = (file, uploadFile) => { };
const columnChange = () => {
  let condi = [];
  let temp = {};
  if (form.code != "" && form.code != undefined) {
    temp = {
      column: "dataCode",
      type: "eq",
      value: form.code,
    };
    condi.push(temp);
  }
  if (form.date != "" && form.date != undefined) {
    temp = {
      column: "statDate",
      type: "ge",
      value: formatDateTime(form.date[0], "yyyy-MM-dd HH:mm:ss"),
    };
    condi.push(temp);
    temp = {
      column: "statDate",
      type: "le",
      value: formatDateTime(form.date[1], "yyyy-MM-dd HH:mm:ss"),
    };
    condi.push(temp);
  }
  if (userInfo.value.roleId != "3") {
    temp = {
      column: "enterpriseCode",
      type: "eq",
      value: userInfo.value.userName,
    };
    condi.push(temp);
  }

  conditions.value = condi;
  getList();
};
doFilterUser();
doDataList();
</script>

<style lang="less" scoped>
.title {
  min-width: 5em;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-card__header {
  max-height: 10vh;
}

.pagination {
  max-height: 3vh;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}

.total-font {
  margin-right: 15px;
  font-weight: 500;
  line-height: 21px;
  color: #595959;
}

.upload-demo {
  margin-right: 10px;
}

.card-footer {
  display: flex;
  justify-content: flex-end;
  align-items: flex-end;
}

.total-font {
  margin-right: 15px;
  font-weight: 500;
  line-height: 21px;
  color: #595959;
}
</style>
